package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"good_srv/good"
	"good_srv/internal/svc"
	"good_srv/models"
	"gorm.io/gorm"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 订单添加
func (l *OrderAddLogic) OrderAdd(in *good.OrderAddRequest) (*good.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	order := models.Order{
		Title:   in.Title,
		OrderSn: in.OrderSn,
		Amount:  float64(in.GoodsPrice) * float64(in.Stock),
		Stock:   in.Stock,
	}
	var db gorm.DB
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err = order.OrderAdd(); err != nil {
		logx.Error("订单添加成功")
		return nil, fmt.Errorf("订单添加成功")
	}
	if in.Num > order.Stock {
		logx.Error("库存不充足")
		return nil, fmt.Errorf("库存不充足")
	}
	orderGood := models.OrderGood{
		GoodsTitle: in.GoodsTitle,
		GoodsPrice: float64(in.GoodsPrice),
		Image:      in.Image,
		GoodsNum:   int(in.GoodsNum),
	}
	if r := recover(); r != nil {
		tx.Rollback()
	}
	if err = orderGood.OrderGoodAdd(); err != nil {
		logx.Error("订单商品添加失败")
		return nil, fmt.Errorf("订单商品添加失败")

	}

	return &good.OrderAddResponse{}, nil
}
